<!-- Login.vue -->
<template>
  <div id="login">
    <div class="login-wrap">
      <el-form
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        label-width="1"
        class="login-form"
      >
        <p class="loginTitle">{{ projectName }}</p>

        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            autocomplete="off"
            clearable
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            autocomplete="off"
            clearable
            @keyup.enter="submitForm(formDataRef)"
          />
        </el-form-item>

        <!-- 语言选择（可选） -->
        <!-- <el-form-item prop="zh">
          <el-select v-model="formData.zh" placeholder="请选择语言" style="width: 100%">
            <el-option label="中文" value="ch" />
            <el-option label="English" value="en" />
            <el-option label="Tiếng Việt" value="vietnamese" />
          </el-select>
        </el-form-item> -->

        <!-- 登录按钮 -->
        <el-form-item class="dis-jsb-ac el-sub">
          <el-button
            type="primary"
            :loading="loading"
            @click="submitForm(formDataRef)"
            style="width: 100%"
          >
            {{ loading ? "登录中..." : "登 录" }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

// API
import {
  login,
  getProjectName,
  loginInfo,
  getBtnPermission,
} from "@/api/index";

// Pinia Store
import { userTokenStore } from "@/store/token";
import { useMenuStore } from "@/store/menu";

// 菜单 & 路由相关
import { menuService } from "@/utils/menuService";
import { generateRoutesFromMenu } from "@/utils/routeGenerator";
import { addDynamicRoutes } from "@/router"; // 新增：动态添加路由的方法

// 类型定义
interface FormState {
  username: string;
  password: string;
  zh: string;
}

const router = useRouter();
const tokenStore = userTokenStore();
const menuStore = useMenuStore();
// 数据
const projectName = ref<string>("艾布斯IEBOX执行力系统");
const loading = ref<boolean>(false);

const formDataRef = ref();
const formData = reactive<FormState>({
  username: "",
  password: "",
  zh: "ch", // 默认中文
});

const rules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

onMounted(async () => {
  const projectData = await getProjectName();
  projectName.value = projectData.projectTitle;
  localStorage.setItem("projectData", JSON.stringify(projectData));
});
// 提交表单
const submitForm = async (formEl: any) => {
  if (!formEl) return;

  // 表单验证
  const valid: boolean = await formEl.validate().catch(() => false);
  if (!valid) return;

  // 防止重复提交
  if (loading.value) return;
  loading.value = true;

  try {
    // 1. 执行登录 API
    const loginRes = await login({
      username: formData.username,
      password: formData.password,
    });

    const tokenStr = loginRes;
    if (!tokenStr) {
      ElMessage.error("登录失败：未获取到 token");
      return;
    }

    tokenStore.setToken(tokenStr);
    localStorage.setItem("token", JSON.stringify(tokenStr)); // 供路由守卫使用
    const userData = await loginInfo();
    localStorage.setItem("UserInfo", JSON.stringify(userData));
    const permission = await getBtnPermission();
    localStorage.setItem("permission", JSON.stringify(permission));
    await menuService.init();
    const menuTree = menuService.getMenuTree();
    const dynamicRoutes = generateRoutesFromMenu(menuTree);
    addDynamicRoutes(dynamicRoutes);
    menuStore.setMenuList(dynamicRoutes);

    ElMessage.success("登录成功");

    await router.replace("/dashboard");
  } catch (error: any) {
    const msg = error.message || "登录失败，请检查用户名或密码";
    ElMessage.error(msg);
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
#login {
  height: 100vh;
  display: flex;
  justify-content: center;
  // background-color: black;
  background: url("@/assets/bg3.png") center/cover no-repeat;
}

.login-wrap {
  width: 24vw;
  height: 36vh;
  // background: url("@/assets/login.png") center/cover no-repeat;
  position: absolute;
  border-radius: 20px;
  // left: 200px;
  top: 30vh;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 8px solid #ffffffa7;
  box-shadow: inset 0px 0px 3px 0px #ffffff6e;
  background-color: rgba(216, 222, 245, 0.548); /* 半透明背景 */
  backdrop-filter: blur(10px); /* 背景模糊 */
  -webkit-backdrop-filter: blur(10px); /* 兼容老版本 Safari */

  @media screen and (max-width: 750px) {
    width: 88vw;
    right: 25px;
    top: 22vh;
  }
}

.login-form {
  width: 80%;

  .loginTitle {
    font-size: 34px;
    font-weight: bold;
    text-align: center;
    color: #157fed;
    margin: auto 0 30px;
  }

  .el-sub {
    margin-top: 52px;
  }
}

:deep(.el-form-item__label) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-input) {
  height: 42px;
}

:deep(.el-button--primary) {
  height: 42px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  height: 42px;
}
</style>
